

<?php 
/*
刷价库的脚本
*/
$start_time=time();
error_reporting(ALL);
	define('DB_HOST', "192.168.1.215:3306");
	define('DB_ROOT', "root");
	define('DB_PASS', "passw0rd");
	define('START_DAY', "2012-11-01");
	define('END_DAY', "2013-05-01");
	$conn = mysql_connect ( DB_HOST, DB_ROOT, DB_PASS );
	mysql_query ( "set names utf8" );
	// mysql_select_db ( "phoenix_stag_prd" );
	mysql_select_db("last_prd");
	//取所有的产品与资源ID
	$sql="SELECT p.id,r.res_id,c.cost,MAX(c.departs_date) max_date,c.stock_num,dp.price_value  
		  FROM product p 
		  LEFT JOIN product_journey j ON p.base_id=j.base_id 
		  LEFT JOIN product_res r ON j.id=r.journey_id 
		  LEFT JOIN resource_date_cost c ON r.res_id=c.res_id
		  LEFT JOIN product_date_price dp ON p.id=dp.product_id 
		  GROUP BY p.id";
	$arr=GetPlan($sql,$conn);
	foreach ($arr as $key => $value) {
		$sql_s=array();
		$price=0;
		if($value['cost']){
			//取价格
			// $sql="SELECT price_value FROM product_date_price WHERE product_id={$value['id']} LIMIT 1";
			// $query=mysql_query($sql);
			// $prices=mysql_fetch_assoc($query);
			$price=intval($value['price_value']);
			//取日期
			// $sql="SELECT MAX(departs_date) max_date, cost,stock_num 
			//       FROM resource_date_cost 
			//       WHERE res_id={$value['res_id']} LIMIT 1";
			// $query=mysql_query($sql);
			// $resouce=mysql_fetch_assoc($query);
			for ($i=START_DAY; $i < END_DAY; $i=date("Y-m-d",strtotime("+1 day",strtotime($i)))) {
				$del_flag=0;
				if($value['max_date']<$i){
					$del_flag=1;
				}
				if($price==0){
					$del_flag=1;
				}else{
					mysql_query("UPDATE product SET lowest_price={$price}  WHERE id={$value['id']}");
				}
				$sql_s[]="({$value['id']},{$price},{$value['stock_num']},NOW(),'{$i}',0,{$value['cost']},{$del_flag})";
			}
		}else{
			for ($i=START_DAY; $i < END_DAY; $i=date("Y-m-d",strtotime("+1 day",strtotime($i)))) {
				$sql_s[]="({$value['id']},0,0,NOW(),'{$i}',0,0,1)";
			}
		}
		
		
		mysql_query("INSERT INTO product_calendar(product_id,price,stock,op_time,departs_date,is_close,cost,del_flag) VALUES ".implode($sql_s, ","));
		echo $value['id']."完成<br>";
	}	

	mysql_query("UPDATE product SET status=0 WHERE lowest_price=0.0");
	mysql_query("UPDATE product SET status=1 WHERE lowest_price!=0.0");




	$end_time=time();
	echo "脚本运行：".($end_time-$start_time)."s";

	function GetPlan($sql, &$conn) {
	
		$rs = mysql_query ( $sql, $conn );
		$data = array ();
		while ( ($row = mysql_fetch_assoc ( $rs )) != false ) {
			$data [] = $row;
		}
		mysql_free_Result ( $rs );
		return $data;
	}
	function GetRow($sql, &$conn) {
		$rs = mysql_query ( $sql, $conn );
		$row = mysql_fetch_assoc ( $rs );
		@mysql_free_Result ( $rs );
		return $row;
	}
	function Query($sql) {
		$res = mysql_query ( $sql );
		return $res;
	}